package com.xinchuang.utils;

import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import org.apache.commons.lang3.StringUtils;

/**
 * @Description: 汉语拼音util
 * @Author: thh
 * @Date: 2024/8/12 17:00
 */
@Slf4j
public class HanyuPinyinUtil {

    /**
     * 汉语转拼音
     *
     * @param chineseWord
     * @return
     */
    public static String chineseToPinyin(String chineseWord) {
        // 创建拼音格式化对象
        try {
            if(StringUtils.isBlank(chineseWord)){
                return chineseWord;
            }
            HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
            format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
            format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
            format.setVCharType(HanyuPinyinVCharType.WITH_V);

            StringBuilder initials = new StringBuilder();
            for (char c : chineseWord.toCharArray()) {
                // 判断是否是中文字符
                if (Character.toString(c).matches("[\\u4e00-\\u9fa5]")) {
                    try {
                        String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
                        if (pinyinArray == null || pinyinArray.length == 0) {
                            initials.append(c);
                        } else {
                            initials.append(pinyinArray[0]);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    // 如果不是中文字符，直接添加
                    initials.append(c);
                }
            }
            return initials.toString();
        } catch (Exception e) {
            log.error("{}转换拼音失败:{}", chineseWord, e.toString(), e);
        }
        return "";
    }

}
